import { AppRouteRecordRaw, PageNameEnum, PagePathEnum } from '../types'
import { markRaw } from 'vue'

// Routing of business modules
const modulesFiles: Recordable = import.meta.globEager('./modules/*.ts')

const modulesRouter = ConvertToRawObject(loadRouter())

export function getModulesRouter(): AppRouteRecordRaw[] { return modulesRouter };

function loadRouter() {
  return Object.keys(modulesFiles).reduce(
    (res: AppRouteRecordRaw[], key: string): AppRouteRecordRaw[] => {
      // Exclude array types
      if (!Array.isArray(modulesFiles[key].default)) {
        res.push(modulesFiles[key].default)
        return res
      } else {
        return res.concat(modulesFiles[key].default)
      }
    },
    [] as AppRouteRecordRaw[]
  )
}

export const loginRouter: AppRouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: 'Login'
    }
  }
]
    
export const oauthRouter: AppRouteRecordRaw[] = [
  {
    path: '/',
    name: 'Authenticate',
    redirect: '/oauth',
    meta: {
      title: 'OAuth'
    },
    children: [
      {
        path: '/oauth',
        name: 'OAuth',
        component: () => import('@/views/oauth.vue'),
        meta: {
          title: 'OAuth'
        },
      }
    ]
  }
]

export const redirectRouter: AppRouteRecordRaw[] = [
  {
    path: '/redirect',
    name: 'Redirect',
    component: () => import('@/views/redirect.vue'),
    meta: {
      title: 'Redirect'
    }
  }
]

// whitelist routing
export const notFoundRouter: AppRouteRecordRaw[] = [
  {
    path: '/:pathMatch(.*)',
    redirect: '/error/404',
    name: 'niversal-error'
  }
]

export const temporaryAuthorizationRouter: AppRouteRecordRaw[] = [
  {
    path: '/temporary-authorization',
    name: 'TemporaryAuthorization',
    component: () => import('@/layout/index.vue'),   
    redirect: '/temporary-authorization/detail',
    meta: {
      title: '临时授权'
    },
    children: [
      {
        path: '/temporary-authorization/detail',
        name: 'temporary-authorization',
        component: () => import('@/views/temporary-authorization/index.vue'),
        meta: {
          title: '临时授权申请',          
        }
      }
    ]
  }
]

export const demoRouter: AppRouteRecordRaw[] = [
  {
    path: '/demo',
    name: 'TwoFactorAuthorization',
    component: () => import('@/views/demo/multi-factor-authorization/index.vue'),
    meta: {
      title: 'Two Factor Authorization'
    }
  }
]

export const whiteListRouter: AppRouteRecordRaw[] = [...loginRouter, ...oauthRouter, ...redirectRouter, ...modulesRouter, ...notFoundRouter, ...temporaryAuthorizationRouter, ...demoRouter]


function ConvertToRawObject(modulesRouter: AppRouteRecordRaw[]) {
  modulesRouter.forEach(e => {
    e.children = markRaw(e.children as AppRouteRecordRaw[])
  })

  return markRaw(modulesRouter)
}